import {Component, OnInit, Input} from '@angular/core';
import {ApiService} from "@core/services/http/api.service";
import {GridConfigService} from 'app/core/config/grid-config.service';
import {GridOptions} from '@ag-grid-community/core';
import {ApesMessageService} from "@shared/apes/message";
import {DatePipe} from "@angular/common";
import {UserAuthService} from "@core/services/user-auth.service";
import { BiService } from '../../../bi.service';

@Component({
  selector: 'apes-shop-traffic-store',
  templateUrl: './shop-traffic-store.component.html',
  styleUrls: ['../../door-tube-center-all.scss']
})
export class ShopTrafficStoreComponent implements OnInit {
  /* 按钮相关 */
  buttonBar = [
    // { hide: true, style: 'default', label: '导出', id: 'action_export' },
    { hide: true, style: 'default', label: '查询', id: 'action_query',loading: false },
    // { hide: true, style: 'default', label: '重置', id: 'action_reset' },
    // { hide: true, style: 'default', label: '展开查询条件', id: 'action_show' },
  ];
  title = '';
  ctx = { model: {} };

  /** Grid 相关 **/
  rowData:any[] = [];
  resultData:any;
  gridOptions:GridOptions;
  pinnedBottomRowData:any[] = [];
  columnDefs:any[] = [];
  height:any = window.innerHeight - 480 + 'px';

  timeList: any = [];       // 日期
  startValue: Date = null;
  endValue: Date = null;
  endDate = null;                     // 默认结束时间
  startDate = null;                   // 默认开始时间 当天
  days: any;

  // 饼图相关
  salesPieData:any;
  shoucidd = [];
  daodiancl = [];
  scdd : any;
  ddcl : any;

  vipPieData:any;
  feihys = [];
  danwhy = [];
  huiys = [];
  fhys : any;
  dwhy : any;
  hys : any;

  wechatPieData:any;
  weixgz = [];
  weigz = [];
  wxygz : any;
  wxwgz : any;

  saleList:any [];
  sale = [];
  saleID: any[];

  userInfo = this.userAuthService.getUserInfoObj();
  companyId = this.userInfo.userAccount.post.company.id;
  companyData: any;
  companyList: any[];

  constructor(private apiService:ApiService,
              private gridConfigService:GridConfigService,
              private msg: ApesMessageService,
              private datePipe: DatePipe,
              private userAuthService: UserAuthService,
              private bi: BiService) {
    this.columnDefs = [
      {headerName: "日期", field: 'TJRQ', },
      {headerName: "门店名称", field: 'MDMC'},
      {headerName: "销售组", field: 'XSZMC'},
      {headerName: "到店总数", field: 'ZDDS'},
      {headerName: "首次到店数", field: 'SCDDS'},
      {headerName: "会员数", field: 'HYS'},
      {headerName: "非会员数", field: 'FHYS'},
      {headerName: "单位车辆数", field: 'DWCLS'},
      {headerName: "微信关注比例", field: 'WXGZBL'},
      {headerName: "保险转化率", field: 'BXZHL'},
      {headerName: "年卡转化率", field: 'NKZHL'},
      {headerName: "环检率", field: 'HJL'},
      {headerName: "快检率", field: 'KJL'},
      {headerName: "注册率", field: 'ZCL'},
      {headerName: "车辆认证率", field: 'CLRZL'},
      {headerName: "36项检查率", field: 'TSJCL'},
      {headerName: "快检报告率", field: 'KJBGL'},
      {headerName: "36项报告率", field: 'TSBGL'}
    ];

    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressExcelExport: true,
      suppressCsvExport: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 20,
      rowHeight: 35
    };
    this.gridOptions.localeText = gridConfigService.getLocaleText();
    this.companyList = [];
    this.companyList.push(this.companyId);
  }

  ngOnInit() {
    // 默认 请求 当天 数据
    this.endDate = new Date();
    this.startDate = new Date(this.endDate.getTime() - (0 * 24 * 60 * 60 * 1000));
    this.timeList.push(this.startDate);
    this.timeList.push(this.endDate);
    this.queryData();
    this.getSaleData();
    this.bi.getCompany(this.userInfo.userAccount.post.localPermit.id).then(value => { this.companyData = value });
  }

  onEvent(data: any) {

    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_query') {
        this.buttonBar[0].loading = true;
        this.queryData();
      }
    }
  }

  // 日期相减
  getTimeChang(d1, d2) {
    let day = 24 * 60 * 60 * 1000;
    try {
      let dateArr = d1.split('-');
      let checkDate = new Date();
      checkDate.setFullYear(dateArr[0], dateArr[1] - 1, dateArr[2]);
      let checkTime = checkDate.getTime();

      let dateArr2 = d2.split('-');
      let checkDate2 = new Date();
      checkDate2.setFullYear(dateArr2[0], dateArr2[1] - 1, dateArr2[2]);
      let checkTime2 = checkDate2.getTime();
      this.days = (checkTime - checkTime2) / day;
      if (this.days <= 31) {
        return 'hide';
      } else {
        return 'show';
      }
    } catch (e) {
      return false;
    }
  }

  // 查询按钮事件
  queryData() {
    // if(this.companyList.length <= 0){
    //   this.companyList.push(this.companyId);
    // }
    this.rowData = [];
    this.shoucidd = [];
    this.daodiancl = [];
    this.scdd = 0;
    this.ddcl = 0;
    this.feihys = [];
    this.danwhy = [];
    this.huiys = [];
    this.fhys = 0;
    this.dwhy = 0;
    this.hys = 0;
    this.weixgz = [];
    this.weigz = [];
    this.wxygz = 0;
    this.wxwgz = 0;
    this.getDate(this.timeList, 'startValue', 'endValue');
    this.getTablesData();
  }

  // 日期转换
  getDate(time: any[], time_ks: string, time_js: string) {
    // debugger;
    let [first, second] = time;
    if (first) {
      this[time_ks] = first.toISOString().slice(0, 10);
    } else {
      this[time_ks] = null;
    }

    if (second) {
      this[time_js] = second.toISOString().slice(0, 10);
    } else {
      this[time_js] = null;
    }

  }

  getTablesData() {
    let data = {
      'interfaceMethod': 'ipmMgzzForAppService.mdDdzcl',
      'pdata': {'STARTDATE': this.startValue, 'ENDDATE': this.endValue,'XSZID': this.saleID, 'companyId': this.companyList}
    };
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj)
            data = data.sort(this.sortarr('XZRQ_SJ'));
            for (let i = 0, len = data.length; i < len; i++) {
              data[i]['TJRQ'] = this.timesChange(data[i]['TJRQ']);
              // 到店车流饼图相关
              this.shoucidd.push(data[i].SCDDS);
              this.daodiancl.push(data[i].ZDDS);
              // 会员饼图相关
              this.feihys.push(data[i].FHYS);
              this.danwhy.push(data[i].DWCLS);
              this.huiys.push(data[i].HYS);
              // 微信饼图相关
              if ((data[i].WXGZBL) !== undefined) {
                this.weigz.push(data[i].WXWGZBL);
                this.weixgz.push(data[i].WXGZBL);
              }
            }

            // 到店车流饼图
            for (let i = 0, len = this.shoucidd.length; i < len; i++) {
              this.scdd += this.shoucidd[i];
            }
            for (let i = 0, len = this.daodiancl.length; i < len; i++) {
              this.ddcl += this.daodiancl[i];
            }
            // 会员饼图
            for (let i = 0, len = this.feihys.length; i < len; i++) {
              this.fhys += this.feihys[i];
            }
            for (let i = 0, len = this.danwhy.length; i < len; i++) {
              this.dwhy += this.danwhy[i];
            }
            for (let i = 0, len = this.huiys.length; i < len; i++) {
              this.hys += this.huiys[i];
            }
            // 微信饼图
            for (let i = 0, len = this.weigz.length; i < len; i++) {
              this.wxwgz += this.weigz[i];
            }
            for (let i = 0, len = this.weixgz.length; i < len; i++) {
              this.wxygz += this.weixgz[i];
            }

            for (let i = 0, len = data.length; i < len; i++) {
              data[i]['NKZHL'] = data[i]['NKZHL'] + '%';
              data[i]['BXZHL'] = data[i]['BXZHL'] + '%';
              data[i]['WXGZBL'] = data[i]['WXGZBL'] + '%';
              data[i]['HJL'] = data[i]['HJL'] + '%';
              data[i]['KJL'] = data[i]['KJL'] + '%';
              data[i]['ZCL'] = data[i]['ZCL'] + '%';
              data[i]['CLRZL'] = data[i]['CLRZL'] + '%';
              data[i]['TSJCL'] = data[i]['TSJCL'] + '%';
              data[i]['KJBGL'] = data[i]['KJBGL'] + '%';
              data[i]['TSBGL'] = data[i]['TSBGL'] + '%';
            }
            this.rowData = data;
            if( this.rowData.length === 0 ) {
              this.msg.info(`未找到满足条件的数据`);
            }

            // // 加载 饼图
            this.salesPieData = this.getSalesTypePie();
            this.vipPieData = this.getVipTypePie();
            this.wechatPieData = this.getWechatPieData();

            this.buttonBar[0].loading = false;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 获取销售组
  getSaleData() {
    let data = {
      'interfaceMethod': 'ipmQueryXszService.queryXszData', 'pdata': { 'MJBJ': 0 },
    };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        // debugger;
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            this.saleList = data;
            this.sale = this.saleList;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 饼图
  getSalesTypePie() {
    return [
      {x: '首次到店', y: this.scdd},
      {x: '到店车辆', y: this.ddcl},
    ];
  }

  getVipTypePie() {
    return [
      {x: '非会员数', y: this.fhys},
      {x: '单位会员', y: this.dwhy},
      {x: '会员数', y: this.hys},
    ];
  }

  getWechatPieData() {
    return [
      {x: '未关注微信', y: this.wxwgz},
      {x: '已关注微信', y: this.wxygz},
    ];
  }

  // 排序 倒序
  sortarr(key) {
    return function (a, b) {
      a[key] == undefined ? a[key] = 0 :
        b[key] == undefined ? b[key] = 0 : 0 ;
      return b[key] - a[key];
    };
  }

  // 时间戳 转换
  timesChange(times:number) {
    if( times ){
      let time = this.datePipe.transform(new Date(times),'yyyy-MM-dd');
      return time;
    }else {
      return '';
    }
  }


}
